package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	"github.com/pelletier/go-toml"
)

type Data struct {
	GitRepo  []string
	GitName  string
	GitEmail string
}

func main() {
	p := flag.String("f", "", "toml file path")
	flag.Parse()
	file, err := os.Open(*p)
	if err != nil {
		logErr(err, "open file")
		return
	}
	defer file.Close()
	data := &Data{}
	if err = toml.NewDecoder(file).Decode(data); err != nil {
		logErr(err, "toml decode")
		return
	}
	for _, repo := range data.GitRepo {
		if err := gitClone(repo); err != nil {
			logErr(err, "gitClone")
			continue
		}
		log.Println("git clone", repo)
		gitConfig(repo, data.GitName, data.GitEmail)
	}
	log.Println("pull code finish")
}

func logErr(err error, msg string) {
	if err == nil {
		return
	}
	log.Printf("[ERR] - %s err: %v", msg, err)
}

func gitClone(repo string) error {
	return exec.Command("git", "clone", repo).Run()
}

func gitConfig(repo, name, email string) {
	if name == "" || email == "" {
		return
	}
	dir := repo[strings.LastIndex(repo, "/")+1 : strings.LastIndex(repo, ".")]
	exec.Command("sh", "-c", fmt.Sprintf("cd %s; git config user.name %s; git config user.email %s; cd ..", dir, name, email)).Run()
}
